import {observable, action, toJS} from 'mobx';
import {WeaTableNew, WeaForm} from 'comsMobx';
import {WeaLocaleProvider} from "ecCom";
import {message, Modal} from "antd";
import _ from 'lodash';
import * as contractManagementApi from '../api/ContractManagementApi';
import {indexOf, isBlank, parseIntValue, null2String} from '../util/CommonUtil';
import LanguageConstant from '../constant/LanguageConstant';

const {getLabel} = WeaLocaleProvider;
const confirm = Modal.confirm;

class EditPermissionStore {

    /**
     * 默认权限设置数据
     *
     * @type {{values: Array, typeShow: string, securityLevelShow: string, minSecurityLevel: number, maxSecurityLevel: number,
     * valuesShow: string, orgrelation: number, type: number}}
     */
    defaultMouldPermissionData = {
        type: 1,
        typeShow: "人员",
        values: [],
        valuesShow: "",
        securityLevelShow: "",
        minSecurityLevel: 0,
        maxSecurityLevel: 100,
        orgRelation: 0,
    };

    /**
     * 组件引用
     * @type {{}}
     */
    refObj = {};

    /**
     * 是否有操作页面的权限
     *
     * @type {boolean}
     */
    @observable authorized = true;

    /**
     * 加载状态
     */
    @observable loading = false;

    /**
     * 模板id
     */
    @observable mouldId = -1;

    /**
     * 权限列表数据
     *
     * @type {Array}
     */
    @observable mouldPermissions = [];

    /**
     * 模板权限数据对象
     */
    @observable mouldPermissionData = _.extend({}, this.defaultMouldPermissionData);

    /**
     * 重置参数
     */
    @action
    reset = () => {
        this.mouldId = -1;
        this.mouldPermissions = [];
        this.mouldPermissionData = _.extend({}, this.defaultMouldPermissionData);
    }

    /**
     * 初始化化
     *
     * @param params
     */
    @action
    init = (params = {}) => {
        this.reset();
        const {mouldId} = params;
        this.mouldId = mouldId;
    }

    /**
     * 更新权限数据
     *
     * @param mouldPermissionData
     */
    @action
    updateMouldPermissionData = (mouldPermissionData) => {
        this.mouldPermissionData = mouldPermissionData;
    }

    /**
     * 更新组件引用
     *
     * @param key
     * @param ref
     */
    updateRefObj = (key, ref) => {
        this.refObj[key] = ref;
    }

    /**
     * 权限类型选择框值改变
     *
     * @param fieldname
     * @param value
     */
    @action
    changePermissionSelect = (fieldname, value) => {
        const mouldPermissionData = toJS(this.mouldPermissionData);
        mouldPermissionData[fieldname] = value;
        this.mouldPermissionData = mouldPermissionData;
    }


    /**
     * 权限浏览框值改变
     *
     * @param fieldname
     * @param ids
     * @param names
     * @param datas
     */
    @action
    changePermissionBrowserField = (fieldname, ids, names, datas) => {
        const mouldPermissionData = toJS(this.mouldPermissionData);
        mouldPermissionData[fieldname] = datas;
        mouldPermissionData[fieldname + "_names"] = names;
        mouldPermissionData[fieldname + "_ids"] = ids;
        this.mouldPermissionData = mouldPermissionData;
    }

    /**
     * 安全级别调整
     *
     * @param fieldname
     * @param value
     */
    @action
    changPermissionSecurityLevel = (fieldname, value) => {
        const mouldPermissionData = toJS(this.mouldPermissionData);
        mouldPermissionData[fieldname] = value;
        this.mouldPermissionData = mouldPermissionData;
    }

    /**
     * 必填提醒
     *
     * @param key
     * @returns {boolean}
     */
    showPermissionError = (key) => {
        const refObj = toJS(this.refObj);
        const domkeyRef = refObj[key];
        domkeyRef.showError();
        return false;
    }

    /**
     * 添加权限
     *
     * @param datas
     * @param addData
     */
    @action
    willAddPermission = (datas, addData) => {
        const mouldPermissionData = toJS(this.mouldPermissionData);
        const mouldPermissions = toJS(this.mouldPermissions);
        const {type, maxSecurityLevel: _maxSecurityLevel, minSecurityLevel: _minSecurityLevel, orgRelation: _orgRelation} = mouldPermissionData;
        let typeShow = "";
        let values = [];
        let valuesShow = "";
        let securityLevelShow = "";
        let minSecurityLevel = parseIntValue("" + _minSecurityLevel, -1);
        let maxSecurityLevel = parseIntValue("" + _maxSecurityLevel, -1);
        let orgRelation = parseIntValue("" + _orgRelation, 0);

        if (type == 1) {
            typeShow = getLabel(LanguageConstant.PERSONNEL, "人员");
            const {user_names, user_ids} = mouldPermissionData;
            valuesShow = null2String(user_names);
            values = user_ids == undefined ? [] : user_ids.split(",");
            if (values.length == 0) {
                this.showPermissionError("user");
                return;
            }
        } else if (type == 2) {
            typeShow = getLabel(LanguageConstant.BRANCH, "分部");
            const {subcompany_names, subcompany_ids} = mouldPermissionData;
            valuesShow = null2String(subcompany_names);
            values = subcompany_ids == undefined ? [] : subcompany_ids.split(",");
            if (values.length == 0) {
                this.showPermissionError("subcompany");
                return;
            }
        } else if (type == 3) {
            typeShow = getLabel(LanguageConstant.DEPARTMENT, "部门");
            const {dept_names, dept_ids} = mouldPermissionData;
            valuesShow = null2String(dept_names);
            values = dept_ids == undefined ? [] : dept_ids.split(",");
            if (values.length == 0) {
                this.showPermissionError("dept");
                return;
            }
        } else if (type == 4) {
            typeShow = getLabel(LanguageConstant.ROLE, "角色");
            const {role_names, role_ids} = mouldPermissionData;
            valuesShow = null2String(role_names);
            values = role_ids == undefined ? [] : role_ids.split(",");
            if (values.length == 0) {
                this.showPermissionError("role");
                return;
            }
        } else if (type == 5) {
            typeShow = getLabel(LanguageConstant.ALL, "所有人");
        } else if (type == 6) {
            typeShow = getLabel(LanguageConstant.JOB, "岗位");
            const {job_names, job_ids} = mouldPermissionData;
            valuesShow = null2String(job_names);
            values = job_ids == undefined ? [] : job_ids.split(",");
            if (values.length == 0) {
                this.showPermissionError("job");
                return;
            }
        }
        if (type == 2 || type == 3) {
            if (orgRelation == 1) {
                typeShow += "-" + getLabel(LanguageConstant.INCLUDE_SUPERIOR, "包含上级");
            } else if (orgRelation == 2) {
                typeShow += "-" + getLabel(LanguageConstant.INCLUDE_SUBORDINATE, "包含下级");
            }
        }
        if (type != 1) {
            if (minSecurityLevel < 0) {
                this.showPermissionError("minSecurityLevel");
                return;
            }
            if (maxSecurityLevel < 0) {
                this.showPermissionError("maxSecurityLevel");
                return;
            }
            securityLevelShow = minSecurityLevel + "-" + maxSecurityLevel;
        }
        const defaultData = {
            typeShow,
            type,
            values,
            valuesShow,
            securityLevelShow,
            minSecurityLevel,
            maxSecurityLevel,
            orgRelation
        };
        addData = {...addData, ...defaultData};
        mouldPermissions.push(addData);
        this.mouldPermissions = mouldPermissions;
        return mouldPermissions;
    }

    /**
     * 删除权限
     *
     * @param datas
     * @param keys
     * @returns {Promise<any>}
     */
    @action
    willDeletePermission = (datas, keys) => {
        return new Promise((resolve, reject) => {
            resolve(true);
        });
    }

    /**
     * 表格数据发生变化
     *
     * @param data
     */
    @action
    onPermissionChange = (data) => {
        this.mouldPermissions = data;
    }

    /**
     * 获取模板权限数据
     *
     * @param params
     */
    @action
    getMouldPermissionTable = (params = {}) => {
        const mouldId = toJS(this.mouldId);
        params = {mouldId, ...params};
        this.loading = true;
        contractManagementApi.getMouldPermissionTable(params).then(res => {
            this.loading = false;
            const {code, data} = res;
            if (code == 200) {
                this.mouldPermissions = data;
            }
        });
    }

    /**
     * 保存模板权限数据
     *
     * @param params
     */
    saveMouldPermissions = (params = {}, successCallback) => {
        const mouldId = toJS(this.mouldId);
        const mouldPermissions = JSON.stringify(toJS(this.mouldPermissions));
        params = {mouldId, mouldPermissions, ...params};
        this.loading = true;
        contractManagementApi.saveMouldPermissions(params).then(res => {
            this.loading = false;
            const {code, data} = res;
            if (code == 200) {
                message.success(getLabel("518560", "操作成功"));
                if (successCallback && _.isFunction(successCallback)) {
                    successCallback();
                }
            } else {
                message.error(getLabel("518561", "操作失败"));
            }
        });
    }

}

export default EditPermissionStore;